package cmd

import (
	"time"

	"gitee.com/zfd81/dbrs/config"

	"gitee.com/zfd81/dbrs/internal/token"

	"github.com/spf13/cobra"
)

const (
	Version     = "1.0"
	Name        = "dbrsctl"
	Description = "A simple cmd line client for dbrs."

	Token_Sign   = "ZFD20220726"
	Token_Secret = "zfd1q2w3e"
	Token_Minute = 1 * 60

	defaultDialTimeout      = 2 * time.Second
	defaultCommandTimeOut   = 5 * time.Second
	defaultKeepAliveTime    = 2 * time.Second
	defaultKeepAliveTimeOut = 6 * time.Second
)

var (
	conf        = config.GetConfig()
	globalFlags = GlobalFlags{}
	rootCmd     = &cobra.Command{
		Use:        Name,
		Short:      Description,
		SuggestFor: []string{"dbrs"},
	}
)

func init() {
	rootCmd.PersistentFlags().StringSliceVar(&globalFlags.Endpoints, "endpoints", []string{"127.0.0.1:8143"}, "gRPC endpoints")
	//rootCmd.PersistentFlags().StringVar(&globalFlags.User, "user", "", "username[:password] for authentication (prompt if password is not supplied)")
	//rootCmd.PersistentFlags().StringVar(&globalFlags.Password, "password", "", "password for authentication (if this option is used, --user option shouldn't include password)")

	rootCmd.CompletionOptions.DisableDefaultCmd = true

	rootCmd.AddCommand(
		NewUserCommand(),
		NewVersionCommand(),
		NewLoadCommand(),
		NewSyncCommand(),
		NewMemberCommand(),
	)

}

func usageFunc(c *cobra.Command) error {
	return UsageFunc(c, Version)
}

func Execute() {
	rootCmd.SetUsageFunc(usageFunc)
	// Make help just show the usage
	rootCmd.SetHelpTemplate(`{{.UsageString}}`)

	if err := rootCmd.Execute(); err != nil {
		ExitWithError(ExitError, err)
	}
}

func getToken() (string, error) {
	claims := token.BrokerClaims{
		Tenant: Token_Sign,
		Sign:   Token_Sign,
		User:   Token_Sign,
	}
	return token.Create(claims, Token_Secret, Token_Minute)
}

func init() {
	cobra.EnablePrefixMatching = true
}
